<!-- Sketchpad -->
<template>


  <div style="display: flex;flex-direction: column; ">
    <!-- <HeaderView>

    </HeaderView> -->

    <div @touchmove.prevent @mousewheel.prevent>


      <history></history>

      <button @click="showLeftDrawer">打开左侧抽屉</button>

      <button @click="showRightDrawer">打开右侧抽屉</button>



      <button @click="addText">add Text</button>
      <button @click="exportImage">export</button>
      <button @click="importPSD">psd</button>
      <input type="file" @change="addImage" accept="image/*" />
      <button @click="addSampleImage">add net Image</button>
      <div style="display: flex; height: calc(100vh - 64px); position: relative;background-color: aquamarine;">
        <!-- <img src="https://nihaojob.github.io/vue-fabric-editor-static/svg/409.svg"/> -->

        <!-- canvas and drawer -->
        <div id="workspace">
          <div class='design-stage-grid' style="display: flex;justify-content: center;align-items: center;">
            <canvas id="canvas"></canvas>
          </div>

          <!-- <Drawer key="leftDrawerRef" ref="leftDrawerRef" direction="left">
            <LeftTemplate></LeftTemplate>
          </Drawer> -->

          <!-- <Drawer key="rightDrawerRef" ref="rightDrawerRef" direction="right" v-if="state.show">
          </Drawer> -->
          <Right v-if="state.show"></Right>

        </div>

      </div>
    </div>
  </div>


</template>

<script setup lang="ts">

import { fabric } from 'fabric';
import { onMounted, reactive, provide } from 'vue';
import { ref } from 'vue'
import Drawer from "./Drawer.vue";
import HeaderView from './HeaderView.vue'
import Editor from '../tool/Editor';
import lockPlugin from '../components/right/components/lock'
let canvas: any = null;

// 创建编辑器
const canvasEditor = new Editor()


const drawer = ref(false)

const host = 'http://' + window.location.hostname//'http://192.168.2.180'
// 使用 ref 创建子组件的引用
const leftDrawerRef = ref(null);
// const rightDrawerRef = ref(null);

// 保存点击的队形
var clickedObject = null

const state = reactive({
  show: false,
  select: null,
  ruler: true,
});

onMounted(() => {

  // console.log(Person)
  canvas = new fabric.Canvas("canvas", {
    // fireRightClick: true,
    // // stopContextMenu: false,
    // controlsAboveOverlay: true,
    // // imageSmoothingEnabled: false,
    // preserveObjectStacking: true,
    // selection: true,
    width: 375,  // 宽度
    height: 667,  // 高度
    fireRightClick: true, // 启用右键，button的数字为3
    stopContextMenu: true, // 禁止默认右键菜单
    controlsAboveOverlay: true, // 超出clipPath后仍然展示控制条
    // imageSmoothingEnabled: false, // 解决文字导出后不清晰问题
    preserveObjectStacking: true, // 当选择画布中的对象时，让对象不在顶层。
  });
  canvasEditor.init(canvas)
  canvasEditor.use(lockPlugin)
    .use(DeleteHotKeyPlugin)
    .use(HistoryPlugin)
    .use(ServersPlugin)
    .use(PsdPlugin)
    .use(FontPlugin, { repoSrc: 'https://www.kuaitu.cc' })
  // canvas.set({
  //           left: 100,
  //           top: 100
  //       });
  // 设置画布的背景颜色
  canvas.backgroundColor = 'white';
  // 隐藏所有对象的控制点，只保留顶部旋转点
  // ['tl', 'bl', 'tr', 'br', 'ml', 'mb', 'mr', 'mt'].forEach(e => {
  //   fabric.Object.prototype.controls[e] = new fabric.Control({
  //     render: () => null,
  //   });
  // })


  const imgURL = 'https://haowallpaper.com/link/common/file/getCroppingImg/15053501456354624'
  canvas.setBackgroundImage(
    imgURL,
    canvas.renderAll.bind(canvas),
    {
      crossOrigin: 'anonymous',
      // scaleX: 0.7,
      // scaleY: 0.7,
    },
  )
  canvas.scaleX = 0.5;
  canvas.scaleY = 0.5;

  canvas.renderAll()



  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  let id = urlParams.getAll('id');


  // 请求的 URL
  const url = `${host}:5000/users?user_id=${id}`;
  // 请求的数据

  // 请求头
  const headers = {
    'Content-Type': 'application/json'
  };
  var data = { user_id: 12 }
  axios.get(url, { data, headers })
    .then(response => {
      // 处理请求成功的情况
      console.log('请求成功', response.data[0]);
      let data = response.data[0]["name"]

      canvas.loadFromJSON(data, canvas.renderAll.bind(canvas)); // 加载数据并渲染到新Canvas上
    })
    .catch(error => {
      // 处理请求失败的情况
      console.error('请求失败', error);
    });

  //  let data = '{"version":"5.4.2","objects":[{"type":"image","version":"5.4.2","originX":"left","originY":"top","left":160.5,"top":306.5,"width":1080,"height":1080,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":0.05,"scaleY":0.05,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://nihaojob.github.io/vue-fabric-editor-static/svg/409.svg","crossOrigin":"anonymous","filters":[]},{"type":"textbox","version":"5.4.2","originX":"left","originY":"top","left":100,"top":100,"width":100,"height":22.6,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"fontFamily":"Times New Roman","fontWeight":"normal","fontSize":20,"text":"文字自定义","underline":false,"overline":false,"linethrough":false,"textAlign":"left","fontStyle":"normal","lineHeight":1.16,"textBackgroundColor":"","charSpacing":0,"styles":[],"direction":"ltr","path":null,"pathStartOffset":0,"pathSide":"left","pathAlign":"baseline","minWidth":20,"splitByGrapheme":false}],"background":"white","backgroundImage":{"type":"image","version":"5.4.2","originX":"left","originY":"top","left":0,"top":0,"width":500,"height":890,"fill":"rgb(0,0,0)","stroke":null,"strokeWidth":0,"strokeDashArray":null,"strokeLineCap":"butt","strokeDashOffset":0,"strokeLineJoin":"miter","strokeUniform":false,"strokeMiterLimit":4,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"backgroundColor":"","fillRule":"nonzero","paintFirst":"fill","globalCompositeOperation":"source-over","skewX":0,"skewY":0,"cropX":0,"cropY":0,"src":"https://haowallpaper.com/link/common/file/getCroppingImg/15053501456354624","crossOrigin":"anonymous","filters":[]}}'
  // canvas.loadFromJSON(data, canvas.renderAll.bind(canvas)); // 加载数据并渲染到新Canvas上

  state.show = true


  provide("fabric", fabric);
  provide('canvas', canvas);

});


const showLeftDrawer = () => {
  if (leftDrawerRef.value) {
  }
}


const showRightDrawer = () => {
  // if (rightDrawerRef.value) {
  //   rightDrawerRef.value.toggleDrawer()
  // }
}

// 添加文字的功能
const addText = () => {
  const text = new fabric.Textbox('文字自定义', {
    left: 100,
    top: 100,
    fontSize: 20,
    selectable: true, // 能否被选中，默认true
  });
  canvas.add(text);
};
import axios from 'axios';
import DeleteHotKeyPlugin from './right/components/del';
import HistoryPlugin from './right/components/historyPlugin';
import ServersPlugin from '@/ServersPlugin';
import PsdPlugin from '@/plugin/PsdPlugin';
import FontPlugin from '@/plugin/FontPlugin'
// 导出图片的功能
const exportImage = () => {

  // const option = _getSaveOption();
  // canvas.setViewportTransform([1, 0, 0, 1, 0, 0]);
  // const dataUrl = canvas.toDataURL(option);

  // // downFile(dataUrl, 'png');

  // // const dataURL = canvas.toDataURL({
  // //   format: 'png',
  // //   quality: 1.0
  // // });
  // const link = document.createElement('a');
  // link.href = dataUrl;
  // link.download = 'canvas-image.png';
  // link.click();

  // 导出为 JSON 数据
  // var jsonData = canvas.getObjects();
  const queryString = window.location.search;
  const urlParams = new URLSearchParams(queryString);
  let id = urlParams.getAll('id')[0];
  var data = { "name": JSON.stringify(canvas.toJSON()), "age": 25, user_id: id };
  console.log(data);


  // 请求的 URL
  const url = host + ':5000/users';
  // 请求的数据

  // 请求头
  const headers = {
    'Content-Type': 'application/json'
  };

  axios.post(url, data, {
    headers: headers
  })
    .then(response => {
      // 处理请求成功的情况
      console.log('请求成功', response.data);
      try {
        const dataURL = canvas.toDataURL({
          format: 'png',
          quality: 1
        });
        const link = document.createElement('a');
        link.href = dataURL;
        link.download = 'composite_image.png';
        link.click();
      } catch (error) {
        console.error('导出图片时出错: ', error);
      }
    })
    .catch(error => {
      // 处理请求失败的情况
      console.error('请求失败', error);
    });




};
const importPSD = (e: any) => {
  canvasEditor.insertPSD().finally();
}
// 添加图片的功能
const addImage = (event: any) => {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e: any) => {
      fabric.Image.fromURL(e.target.result, (img) => {
        img.set({
          left: 100,
          top: 100,
          scaleX: 0.5,
          scaleY: 0.5,
          selectable: true, // 是否可以选择
          hasControls: true, // 是否显示控件（旋转、缩放等）
          hasBorders: true, // 是否显示边框
          lockMovementX: false, // 是否锁定水平移动
          lockMovementY: false, // 是否锁定垂直移动
          lockScalingX: false, // 是否锁定水平缩放
          lockScalingY: false, // 是否锁定垂直缩放
          lockRotation: false,  // 是否锁定旋转
          crossOrigin: 'anonymous',
          // 使图像可以被拖动
          evented: true,
          // 使图像可以被旋转
          hasRotatingPoint: true,
          // 使图像可以被缩放
          lockUniScaling: true,
          // 允许调整图像大小
          cornerSize: 10,
          // 设置角的颜色
          cornerColor: 'red',
        });
        img.crossOrigin = 'anonymous';
        canvas.add(img);
        canvas.setActiveObject(img);
        canvas.renderAll()
      }, { crossOrigin: 'anonymous' });
    };
    reader.readAsDataURL(file);
  }
};


let indexImage = 0
// 添加示例图片的功能
const addSampleImage = () => {
  console.log(`output->img`)
  const imageUrl = `https://nihaojob.github.io/vue-fabric-editor-static/svg/${409 + indexImage}.svg`; // 替换为您的图片 URL
  // creatImg(imageUrl,0.5,canvas)
  fabric.Image.fromURL(imageUrl, (img) => {
    img.crossOrigin = 'anonymous';
    img.set({
      // left: 200 - indexImage * 50,
      // top: 200 - indexImage * 50,
      scaleX: 0.05,
      scaleY: 0.05,
      // width: 500,
      // height: 500,
      selectable: true,
      hasBorders: false,
      hasControls: true, // 显示控制手柄
      lockMovementX: false, // 允许水平移动，可设置为 true 禁止水平移动
      lockMovementY: false, // 允许垂直移动，可设置为 true 禁止垂直移动
      crossOrigin: 'anonymous'
    });
    canvas.add(img);
    // img.top = 10;
    // canvas.setActiveObject(img);

    canvas.renderAll()
    canvas.viewportCenterObject(img)
    console.log(`output->img`, img)
    indexImage--;
  }, { crossOrigin: 'anonymous' });
};

// https://nihaojob.github.io/vue-fabric-editor-static/svg/409.svg


provide('canvasEditor', canvasEditor)
</script>



<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
#workspace {
  flex: 1;
  width: 100vw;
  position: relative;
  background: #f1f1f1;
  overflow: hidden;



}

.custom {
  width: 20% !important;
  background-color: #42b983;
}

/* // 画布内阴影 */
.inside-shadow {
  position: absolute;
  /* width: 100%; */
  height: 100%;
  box-shadow: inset 0 0 9px 2px #0000001f;
  z-index: 2;
  pointer-events: none;
}

/* 网格背景 */
.design-stage-grid {
  position: absolute;
  /* top: 0;
  left: 0;
  right: 0;
  bottom: 0; */
  background-color: #d0d0d0;
  height: 100%;
  width: 100vw;
  --offsetX: 0px;
  --offsetY: 0px;
  --size: 16px;
  --color: #dcdede;
  background-image: linear-gradient(45deg,
      var(--color) 25%,
      transparent 0,
      transparent 75%,
      var(--color) 0),
    linear-gradient(45deg, var(--color) 25%, transparent 0, transparent 75%, var(--color) 0);
  background-position: var(--offsetX) var(--offsetY),
    calc(var(--size) + var(--offsetX)) calc(var(--size) + var(--offsetY));
  background-size: calc(var(--size) * 2) calc(var(--size) * 2);
}

canvas {
  border: 2px solid #000;
}
</style>
